package com.product.magina.dingtalk.exception;

import com.magina.common.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ExecutionException;

@ControllerAdvice
@Slf4j
public class GobalExpectionHandler extends ExceptionHandlers {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Response<String> throwable(Exception exception) {

        if(exception instanceof ExecutionException){
            log.error(exception.getCause().getMessage());
            exception.printStackTrace();
            return Response.fail("5998","sync_execution_error",exception.getCause().getMessage());
        }
        if(exception instanceof InvalidDataAccessApiUsageException){
            log.error(exception.getCause().getMessage());
            exception.printStackTrace();
            return Response.fail("5996","sql_data_error",exception.getMessage());//catch 客户sql异常
        }
        if(exception instanceof MyBatisSystemException){
            log.error(exception.getCause().getMessage());
            if(exception.getCause() instanceof TooManyResultsException){
                exception.printStackTrace();
                return Response.fail("5994","sql查询结果不唯一,请确认业务逻辑!",exception.getMessage() );//catch 客户sql异常
            }
            exception.printStackTrace();
            return Response.fail("5995","sql_data_error",exception.getMessage());//catch 客户sql异常
        }
        log.error( exception.getMessage());
        exception.printStackTrace();
        return Response.fail("5999", "msg_system_error", exception.toString());
    }

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    public Response<String> iae(Exception ex) {
        log.error("IllegalArgumentException:"+ ex.getMessage());
        ex.printStackTrace();
        return Response.fail("5000", ex.getMessage(),"IllegalArgumentException");
    }

    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public Response<String> run(Exception ex) {
        log.error("RuntimeException", ex);
        ex.printStackTrace();
        return Response.fail("5993",StringUtils.isEmpty(ex.getMessage()) ? "空指针异常" : ex.getMessage(),"check_data_error");//catch 客户sql异常;
    }


}

